# -*- coding: utf-8 -*-
import math
import os
import random
import sys

import cv2
import natsort as nt
from osgeo import gdal
from gdal_app import util
from rest_framework.views import APIView
from rest_framework.response import Response
import json
import requests


class GRID(APIView):
    def post(self, request):
        files = request.POST.get('files')
        file_dict = json.loads(files)
        first_key = next(iter(file_dict))
        first_value = file_dict[first_key]
        # os.chdir(r'E:/data')  # 切换路径到待处理图像所在文件夹
        # file_name = r"D:\imgs\monitor\buildingExtractionIndexed.tif"
        # file_name = r"D:\imgs\Input\buildingExtractionIndexed.tif"
        print(first_value)
        dataset = gdal.Open(first_value)
        minx, xres, xskew, maxy, yskew, yres = dataset.GetGeoTransform()
        proj, geotrans, data = util.read_img(first_value)  # 读数据
        print(proj)
        print(geotrans)
        print(data.shape)
        if len(data.shape) == 3:
            bands, height, width = data.shape
            # 切割像素
            size = 1500
            step = 500
            y = math.ceil((height - size) // step) + 1
            x = math.ceil((width - size) // step) + 1
            print(x)
            print(y)
            for j in range(y):  # 切割成小图
                for i in range(x):
                    if j != y - 1:
                        if i != x - 1:
                            cur_image = data[bands - 1, i * step:i * step + size, j * step:j * step + size]
                            lon = minx + xres * step * j
                            lat = maxy + yres * (i * step)
                            util.write_img(r'D:\faceWatch\temptif/{}_{}.tif'.format(i, j), proj,
                                             lon, lat, xres, yres, cur_image)  # 写数据
                        else:
                            cur_image = data[bands - 1, -size:, j * step:j * step + size]
                            lon = minx + xres * step * j
                            lat = maxy + yres * (i * step)
                            util.write_img(r'D:\faceWatch\temptif/{}_{}.tif'.format(i, j), proj,
                                             lon, lat, xres, yres, cur_image)  # 写数据
                    else:
                        if i != x - 1:
                            cur_image = data[bands - 1, i * step:i * step + size, -size:]
                            lon = minx + xres * step * j
                            lat = maxy + yres * (i * step)
                            util.write_img(r'D:\faceWatch\temptif/{}_{}.tif'.format(i, j), proj,
                                             lon, lat, xres, yres, cur_image)  # 写数据
                        else:
                            cur_image = data[bands - 1, -size:, -size:]
                            lon = minx + xres * step * j
                            lat = maxy + yres * (i * step)
                            util.write_img(r'D:\faceWatch\temptif/{}_{}.tif'.format(i, j), proj,
                                             lon, lat, xres, yres, cur_image)  # 写数据
        else:
            height, width = data.shape
            size = 1500
            step = 500
            y = math.ceil((height - size) // step) + 1
            x = math.ceil((width - size) // step) + 1
            print(x)
            print(y)
            for j in range(y):  # 切割成小图
                for i in range(x):
                    if j != y - 1:
                        if i != x - 1:
                            cur_image = data[i * step:i * step + size, j * step:j * step + size]
                            lon = minx + xres * step * j
                            lat = maxy + yres * (i * step)
                            util.write_img(r'D:\faceWatch\temptif/{}_{}.tif'.format(i, j), proj,
                                           lon, lat, xres, yres, cur_image)  # 写数据
                        else:
                            cur_image = data[-size:, j * step:j * step + size]
                            lon = minx + xres * step * j
                            lat = maxy + yres * (i * step)
                            util.write_img(r'D:\faceWatch\temptif/{}_{}.tif'.format(i, j), proj,
                                           lon, lat, xres, yres, cur_image)  # 写数据
                    else:
                        if i != x - 1:
                            cur_image = data[i * step:i * step + size, -size:]
                            lon = minx + xres * step * j
                            lat = maxy + yres * (i * step)
                            util.write_img(r'D:\faceWatch\temptif/{}_{}.tif'.format(i, j), proj,
                                           lon, lat, xres, yres, cur_image)  # 写数据
                        else:
                            cur_image = data[-size:, -size:]
                            lon = minx + xres * step * j
                            lat = maxy + yres * (i * step)
                            util.write_img(r'D:\faceWatch\temptif/{}_{}.tif'.format(i, j), proj,
                                           lon, lat, xres, yres, cur_image)  # 写数据
        # 找到切图文件所在的文件夹，然后把文件夹里包含的文件(以.tif/.jpg为后缀的)名写入到json文件中
        id = -1
        path = "D:\\faceWatch\\temptif\\"
        file_list = nt.natsorted(os.listdir(path))
        print(file_list)
        jsonObject = []
        for filename in file_list:
            id += 1
            print("=======write======")
            # print(filename)
            dirs = path + filename
            img = cv2.imread(dirs)
            size = img.shape
            # print(size)
            height = size[0]
            width = size[1]
            # print(height)
            # print(width)
            if id <= 0:
                test_dict = {
                                "info": {"descroption": "null", "url": "null", "version": "null", "year": 2023,
                                         "contributor": "null",
                                         "date_created": "2023-06-06"},
                                "licenses": [{"url": "null", "id": 0, "name": "null"}],
                                "images": [
                                    {"license": 0, "url": "null", "file_name": filename, "height": height,
                                     "width": width, "date_captured": "null", "id": id}
                                ],
                                "type": "instances",
                                "annotations": [],
                                "categories": [
                                    {
                                        "supercategory": "null",
                                        "id": 1,
                                        "name": "ship"
                                    }
                                ]
                            },
                json_str = json.dumps(test_dict)
                new_dict = json.loads(json_str)
                with open(r"D:\Pycharm\django-test\config\record.json", "w", encoding='utf-8') as fw:
                    json.dump(new_dict, fw, indent=4, ensure_ascii=False)
                    print("\n")
            else:
                test_dict_content = {"license": 0, "url": "null", "file_name": filename, "height": height,
                                     "width": width, "date_captured": "null", "id": id}
                jsonObject.append(test_dict_content)
                json_str = json.dumps(jsonObject)
                new_dict = json.loads(json_str)
                with open(r"D:\Pycharm\django-test\config\record1.json", "w", encoding='utf-8') as fw:
                    json.dump(new_dict, fw, indent=4, ensure_ascii=False)
                    print("\n")
        with open(r"D:\Pycharm\django-test\config\record.json") as fin1:
            data1 = json.load(fin1)
        with open(r"D:\Pycharm\django-test\config\record1.json") as fin2:
            data2 = json.load(fin2)
        data1[0]["images"].extend(
            data2)  # extend() 方法用于将一个可迭代对象中的元素逐个追加到列表中。它将迭代遍历可迭代对象并将每个元素逐个添加到列表中。使用 extend() 将 data2
        # 中的元素逐个添加到 data1[0]["images"] 中，可以保持列表的扁平结构，避免额外的嵌套。补充：append方法用于将一个元素追加到列表的末尾，作为一个单独的元素。如果使用append()将data2
        # 添加到data1[0]["images"]中，导致最外层多了一个列表。
        json_str = json.dumps(data1)
        print(json_str)
        old_dict = json_str[1:-1]
        print(old_dict)
        new_dict = json.loads(old_dict)
        print(new_dict)
        print(type(new_dict))
        number = random.randint(0, 10000)
        json_name = "testJson_" + str(number) + ".json"
        with open(r"D:/Pycharm/django-test/config/" + json_name, "w") as fin3:
            json.dump(new_dict, fin3)
        print(number)
        url = 'http://127.0.0.1:8000/sar/sar_post/'
        headers = {'Content-type': 'application/json'}
        jsonName = json_name  # jsonName负责传json文件名给算法进行测试集识别
        data = {'url': "D:\imgs\pyClip", 'jsonName': jsonName}

        response = requests.post(url, data=json.dumps(data), headers=headers)
        return Response({"msg": "success", "code": 200})
